from django.db import models
from django.template.defaultfilters import slugify

class AutoSlugField(models.SlugField):
    def __init__(self, populate_from, force_update=False, *args, **kwargs):
        kwargs['editable'] = kwargs.get('editable', False)
        
        self.populate_from = populate_from
        self.force_update = force_update
        
        super(AutoSlugField, self).__init__(*args, **kwargs)
    
    def pre_save(self, model_instance, add):
        slug = getattr(model_instance, self.attname)
        
        if add and not slug or self.force_update:
            value = slugify(getattr(model_instance, self.populate_from))
            setattr(model_instance, self.attname, value)
            return value
        else:
            return slug